package com.lk.filter;

import com.lk.beans.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*

非法访问拦截

可放行的资源
1.登录注册界面
2.静态资源 css、js、图片
3.
4.登录成功后可放行(判断session中是否存在user)



    免登录功能
    通过Cookie对象实现
    什么时候需要免登录？
    当用户处于未登录状态且需要登录时，调用自动登录功能
    实现：
        从cookie对象中获取用户的姓名与密码，自动执行登录操作
            1.获取Cookie数组 request.getCookies();
            2.判断Cookie数组
            3.遍历Cookie数组 找到name为user的Cookie对象
            4.得到对应cookie对象的value
            5.通过split（）方法分割字符串
            6.分别得到姓名和密码
            7.请求转发 user?actionName=login&userName=xxx&userPwd=xxx
 */
@WebFilter("/*")
public class LoginAccessFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String path = request.getRequestURI();//格式：项目路径/资源路径

        if(path.contains("/login.jsp")||path.contains("/static")){
            filterChain.doFilter(request,response);
            return;
        }
        if(path.contains("/user")){
            String actionName=request.getParameter("actionName");
            if("login".equals(actionName)){
                filterChain.doFilter(request,response);
                return;
            }
        }
        User user=(User) request.getSession().getAttribute("user");
        if(user!=null){
            filterChain.doFilter(request,response);
            return;
        }

        /*

        免登录

         */
        Cookie[] cookies=request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for(Cookie cookie:cookies){
                if("user".equals(cookie.getName())){
                    String value=cookie.getValue();//admin-123456
                    String[] val=value.split("-");
                    String userName=val[0];
                    String userPwd=val[1];
                    String url="user?actionName=login&userName="+userName+"&userPwd="+userPwd;
                    request.getRequestDispatcher(url).forward(request,response);
                    return;
                }
            }
        }
        response.sendRedirect("login.jsp");
    }

    @Override
    public void destroy() {

    }
}
